package keeto.com.vn.classified.ui;


import it.sephiroth.android.library.widget.AbsHListView;
import it.sephiroth.android.library.widget.AbsHListView.OnScrollListener;
import it.sephiroth.android.library.widget.HListView;

import java.util.ArrayList;

import com.androidquery.AQuery;
import com.androidquery.util.AQUtility;

import keeto.com.vn.classfied.model.Area;
import keeto.com.vn.classified.adapter.HomeProductAdapter;
import keeto.com.vn.classified.core.ClassifiedCore;
import keeto.com.vn.classified.core.ClassifiedListener;
import keeto.com.vn.classified.database.BuiltinService;
import keeto.com.vn.classified.database.BuiltinServiceManager;
import keeto.com.vn.classified.manager.IAManager;
import keeto.com.vn.classified.menutab.IMenuTabConfig;
import keeto.com.vn.classified.menutab.MenuTabAdapter;
import keeto.com.vn.classified.network.IProtocol;
import keeto.com.vn.classified.network.entity.ListItemEntity;
import keeto.com.vn.classified.widgets.LogoutDialog;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.text.Html;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class HomeClassifeldActivity extends Activity implements OnClickListener{

	private ImageButton bt_title_na_menu;
	private ImageButton bt_title_logo_home;
	private ImageView bt_title_search_home;
	private Button btn_editor_warranty;
	private EditText edt_search_warranty_store;
	private ImageButton btn_search_warranty;
	private TextView tv_view_all1;
	private TextView tv_view_all2;
	private TextView tv_view_all3;
	private TextView tv_link_web1;
	private TextView tv_link_web2;
	private TextView tv_link_web3;
	private ProgressBar pb_loading1;
	private ProgressBar pb_loading2;
	private ProgressBar pb_loading3;
	private HListView vp_hp_pager1;
	private HListView vp_hp_pager2;
	private HListView vp_hp_pager3;
	private Area mArea = null;

	int screenWith;
	/*
	 * init Menu Tab
	 */
	private BuiltinService builtservice = null;
	private BuiltinServiceManager mBuiltinServiceManager = null;
	private DrawerLayout drawerLayoutMenuTab;
	private ListView mDrawerList;
	private MenuTabAdapter tabAdapter;


	private HomeListener mListener = new HomeListener();
	View footerView;
	private ProgressBar pb_pg_load_bottom;
	private int PageLimit = 6;
	private int PageNumber = 1;
	private int PageCount;
	private ArrayList<ListItemEntity> arrNewProduct = new ArrayList<ListItemEntity>();
	private ArrayList<ListItemEntity> arrInterestProduct = new ArrayList<ListItemEntity>();
	private ArrayList<ListItemEntity> arrRatingProduct = new ArrayList<ListItemEntity>();

	private String mAction= ""; 
	private AQuery mQuery ;

	HomeProductAdapter adapter_latest, adapter_interest, adapter_appreciate;

	private Intent intent; 
	public static final int LOAD_DATA_HOME = 1000;
	public static final String ACTION_LOAD_DATA_HOME = "LoadDataHome";

	public static void actionLaunch(Context context) {
		Intent intent = new Intent(context, HomeClassifeldActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_NO_ANIMATION);
		context.startActivity(intent);
	}
	public static void actionLaunchAfterLoadData(Activity context) {
		Intent i = new Intent(context, HomeClassifeldActivity.class);
		i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK |Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_NO_ANIMATION);
		i.setAction(ACTION_LOAD_DATA_HOME);
		context.startActivityForResult(i,LOAD_DATA_HOME);
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		intent = getIntent();
		mAction = intent.getAction();

		mArea =  IAManager.getInstance(this).getMyArea();
		mBuiltinServiceManager = BuiltinServiceManager.getInstance(this);
		builtservice = mBuiltinServiceManager.getBuitinService();
		mQuery = new AQuery(this);
		initView();
		initMenuData();
		adapter_latest = new HomeProductAdapter(HomeClassifeldActivity.this, arrNewProduct,mQuery);
		adapter_interest = new HomeProductAdapter(HomeClassifeldActivity.this, arrInterestProduct,mQuery);
		adapter_appreciate = new HomeProductAdapter(HomeClassifeldActivity.this, arrRatingProduct,mQuery);
		vp_hp_pager1.setAdapter(adapter_latest);
		vp_hp_pager2.setAdapter(adapter_interest);
		vp_hp_pager3.setAdapter(adapter_appreciate);
		getData();
	}

	private void initView() {
		bt_title_na_menu = (ImageButton) findViewById(R.id.btn_title_na_menu);
		bt_title_logo_home = (ImageButton) findViewById(R.id.btn_title_logo_home);		
		bt_title_search_home = (ImageView) findViewById(R.id.btn_title_search_home);
		drawerLayoutMenuTab = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.drawer);
		btn_editor_warranty = (Button) findViewById(R.id.btn_editor_warranty);
		btn_editor_warranty.setHint(Html.fromHtml(getResources().getString(R.string.name_titile_layout)));
		btn_editor_warranty.setOnClickListener(this);
		btn_search_warranty = (ImageButton) findViewById(R.id.btn_search_warranty);
		btn_search_warranty.setOnClickListener(this);
		edt_search_warranty_store = (EditText) findViewById(R.id.edt_search_warranty_store);
		edt_search_warranty_store.setHint(Html.fromHtml(getResources().getString(R.string.search_product)));
		edt_search_warranty_store.setInputType(TRIM_MEMORY_COMPLETE);
		edt_search_warranty_store.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
					String keysearch = edt_search_warranty_store.getText().toString();
					ProductsActivity.actionSearchGlobalbyKey(HomeClassifeldActivity.this,keysearch);
				}
				return false;
			}
		});
		tv_view_all1 = (TextView) findViewById(R.id.view_all1);
		tv_view_all1.setOnClickListener(this);
		tv_view_all2 = (TextView) findViewById(R.id.view_all2);
		tv_view_all2.setOnClickListener(this);
		tv_view_all3 = (TextView) findViewById(R.id.view_all3);
		tv_view_all3.setOnClickListener(this);
		tv_link_web1 = (TextView) findViewById(R.id.link_web1);
		tv_link_web2 = (TextView) findViewById(R.id.link_web2);
		tv_link_web3 = (TextView) findViewById(R.id.link_web3);
		pb_loading1 = (ProgressBar) findViewById(R.id.loading1);
		pb_loading2 = (ProgressBar) findViewById(R.id.loading2);
		pb_loading3 = (ProgressBar) findViewById(R.id.loading3);
		vp_hp_pager1 = (HListView) findViewById(R.id.hp_pager1);
		vp_hp_pager2 = (HListView) findViewById(R.id.hp_pager2);
		vp_hp_pager3 = (HListView) findViewById(R.id.hp_pager3);
		footerView =  ((LayoutInflater)HomeClassifeldActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_listview, null, false);
		vp_hp_pager1.addFooterView(footerView);
		vp_hp_pager2.addFooterView(footerView);
		vp_hp_pager3.addFooterView(footerView);
		pb_pg_load_bottom = (ProgressBar) footerView.findViewById(R.id.pg_load_bottom);
		vp_hp_pager1.setOnScrollListener(new AbsHListView.OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsHListView view, int scrollState) {
				switch (scrollState) {
				case OnScrollListener.SCROLL_STATE_IDLE:
					if(PageNumber < PageCount){
						PageNumber++;
						ClassifiedCore.getInstance(HomeClassifeldActivity.this).taskGetAndroidProductAd(mListener, PageLimit, "1",PageNumber,mArea.getRemoteId());
						pb_pg_load_bottom.setVisibility(View.VISIBLE);
					}
					break;
				default:
					break;
				}
			}
			@Override
			public void onScroll(AbsHListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {}
		});

		vp_hp_pager2.setOnScrollListener(new AbsHListView.OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsHListView view, int scrollState) {
				switch (scrollState) {
				case OnScrollListener.SCROLL_STATE_IDLE:
					if(PageNumber < PageCount){
						PageNumber++;
						ClassifiedCore.getInstance(HomeClassifeldActivity.this).taskGetAndroidProductAd(mListener, PageLimit, "3",PageNumber,mArea.getRemoteId());
						pb_pg_load_bottom.setVisibility(View.VISIBLE);
					}
					break;
				default:
					break;
				}
			}
			@Override
			public void onScroll(AbsHListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {}
		});

		vp_hp_pager3.setOnScrollListener(new AbsHListView.OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsHListView view, int scrollState) {
				switch (scrollState) {
				case OnScrollListener.SCROLL_STATE_IDLE:
					if(PageNumber < PageCount){
						PageNumber++;
						ClassifiedCore.getInstance(HomeClassifeldActivity.this).taskGetAndroidProductAd(mListener, PageLimit, "2",PageNumber,mArea.getRemoteId());
						pb_pg_load_bottom.setVisibility(View.VISIBLE);
					}
					break;
				default:
					break;
				}
			}
			@Override
			public void onScroll(AbsHListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {}
		});

		btn_editor_warranty.setOnClickListener(this);
		bt_title_na_menu.setOnClickListener(this);
		bt_title_search_home.setOnClickListener(this);
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mBuiltinServiceManager = BuiltinServiceManager.getInstance(this);
		builtservice = mBuiltinServiceManager.getBuitinService();
		initMenuData();
		mArea =  IAManager.getInstance(this).getMyArea();
		if (tabAdapter != null && mArea != null){
			for (int i=0;i<tabAdapter.getTabModel().size();i++){
				if (tabAdapter.getTabModel().get(i).getMenutab_key() == IMenuTabConfig.MENU_AREA){
					tabAdapter.getTabModel().get(i).setNameMenu(mArea.getName());
					break;
				}
			}
			tabAdapter.notifyDataSetChanged();
		}
	}

	private void getData() {
		ClassifiedCore.getInstance(this.getApplication()).taskGetAndroidProductAd(mListener, PageLimit, "1",1,mArea.getRemoteId());
		ClassifiedCore.getInstance(this.getApplication()).taskGetAndroidProductAd(mListener, PageLimit, "2",1,mArea.getRemoteId());
		ClassifiedCore.getInstance(this.getApplication()).taskGetAndroidProductAd(mListener, PageLimit, "3",1,mArea.getRemoteId());
	}

	private void initMenuData(){
		if (builtservice == null){
			tabAdapter = new MenuTabAdapter(HomeClassifeldActivity.this, false,IMenuTabConfig.MENU_HOME);
		}else{
			tabAdapter = new MenuTabAdapter(HomeClassifeldActivity.this, true,IMenuTabConfig.MENU_HOME);
			tabAdapter.setUsername(builtservice.getUserName());
		}
		mDrawerList.setAdapter(tabAdapter);
		mDrawerList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (tabAdapter.getTabModel() != null){
					int index = tabAdapter.getTabModel().get(position).getMenutab_key();
					switch (index) {
					case IMenuTabConfig.MENU_HOME:
						drawerLayoutMenuTab.closeDrawers();
						CategoriesActivity.launchCategoriesView(HomeClassifeldActivity.this, mArea);
						break;
					case IMenuTabConfig.MENU_AREA:
						drawerLayoutMenuTab.closeDrawers();
						ProvincesActivity.actionChangeCityLaunch(HomeClassifeldActivity.this);
						break;
					case IMenuTabConfig.MENU_PROFILE_NAME:
						if(builtservice==null){
							drawerLayoutMenuTab.closeDrawers();
							LoginActivity.actionLaunch(HomeClassifeldActivity.this);
						}else{
							drawerLayoutMenuTab.closeDrawers();
							UserProfileActivity.actionLaunch(HomeClassifeldActivity.this);
						}

						break;
					case IMenuTabConfig.MENU_INTEREST:
						drawerLayoutMenuTab.closeDrawers();
						FavoritesActivity.actionViewFavorites(HomeClassifeldActivity.this);
						break;
					case IMenuTabConfig.MENU_POSTED:
						drawerLayoutMenuTab.closeDrawers();
						FavoritesActivity.actionViewPosted(HomeClassifeldActivity.this);
						break;
					case IMenuTabConfig.MENU_HISTORY:
						drawerLayoutMenuTab.closeDrawers();
						FavoritesActivity.actionViewHistory(HomeClassifeldActivity.this);

						break;
					case IMenuTabConfig.MENU_LOGOUT:
						drawerLayoutMenuTab.closeDrawers();
						LogoutDialog dialog= new LogoutDialog(HomeClassifeldActivity.this);
						dialog.show();
						break;

					case IMenuTabConfig.MENU_POST:
						drawerLayoutMenuTab.closeDrawers();
						PostProductActivity.actionLaunch(HomeClassifeldActivity.this);
						break;

					default:
						break;
					}

				}
			}
		});

	}
	class HomeListener extends ClassifiedListener{
		@Override
		public void finishGetProductAd(final int returnCode, final ArrayList<ListItemEntity> list_latest,
				final ArrayList<ListItemEntity> list_interest, final ArrayList<ListItemEntity> list_appreciate, final int pageCount) {
			super.finishGetProductAd(returnCode, list_latest, list_interest, list_appreciate, pageCount);
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					if (returnCode == IProtocol.STATUS_CODE_OK_200) {
						PageCount = pageCount;
						pb_pg_load_bottom.setVisibility(View.GONE);
						if (list_latest != null && list_latest.size() > 0) {
							//							arrNewProduct.clear();
							arrNewProduct.addAll(list_latest);
							adapter_latest.notifyDataSetChanged();
							pb_loading1.setVisibility(View.GONE);
						}
						if (list_interest != null && list_interest.size() > 0) {
							//							arrInterestProduct.clear();
							arrInterestProduct.addAll(list_interest);
							adapter_interest.notifyDataSetChanged();
							pb_loading2.setVisibility(View.GONE);
						}
						if (list_appreciate != null && list_appreciate.size() > 0) {
							//							arrRatingProduct.clear();
							arrRatingProduct.addAll(list_appreciate);
							adapter_appreciate.notifyDataSetChanged();
							pb_loading3.setVisibility(View.GONE);
							if(mAction != null){
								if (mAction.equals(ACTION_LOAD_DATA_HOME)){
									HomeClassifeldActivity.this.setResult(RESULT_OK, intent);
								}
							}

						}
					} 

				}
			});
		}
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_title_na_menu:
			if (drawerLayoutMenuTab.isDrawerOpen(mDrawerList)) {
				drawerLayoutMenuTab.closeDrawers();
			} else {
				drawerLayoutMenuTab.openDrawer(mDrawerList);
			}
			break;
		case R.id.btn_title_search_home:
			ProductsActivity.actionSearchGlobal(this);
			break;
		case R.id.btn_editor_warranty:
			CategoriesActivity.launchCategoriesView(HomeClassifeldActivity.this, mArea);
			break;
		case R.id.btn_search_warranty:
			String keysearch = edt_search_warranty_store.getText().toString();
			ProductsActivity.actionSearchGlobalbyKey(HomeClassifeldActivity.this,keysearch);

			break;
		case R.id.view_all1:
			ListCateproductActivity.actionLaunch(HomeClassifeldActivity.this,tv_link_web1.getText().toString());
			break;
		case R.id.view_all2:
			ListCateproductActivity.actionLaunch(HomeClassifeldActivity.this,tv_link_web2.getText().toString());
			break;
		case R.id.view_all3:
			ListCateproductActivity.actionLaunch(HomeClassifeldActivity.this,tv_link_web3.getText().toString());
			break;


		default:
			break;
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == ProvincesActivity.ACTION_CHANGE_AREA && resultCode == RESULT_OK){
			mArea =  IAManager.getInstance(this).getMyArea();
			if (tabAdapter != null && mArea != null){
				for (int i=0;i<tabAdapter.getTabModel().size();i++){
					if (tabAdapter.getTabModel().get(i).getMenutab_key() == IMenuTabConfig.MENU_AREA){
						tabAdapter.getTabModel().get(i).setNameMenu(mArea.getName());
						break;
					}
				}
				tabAdapter.notifyDataSetChanged();
				getData();
			}
		}
	}
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (drawerLayoutMenuTab != null && drawerLayoutMenuTab.isDrawerOpen(GravityCompat.START)){
			drawerLayoutMenuTab.closeDrawers();
			return;
		}else{
			super.onBackPressed();
		}
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(isTaskRoot()){

			long triggerSize = 3000000; 
			long targetSize = 2000000;      
			AQUtility.cleanCacheAsync(this, triggerSize, targetSize);
		}
	}

}
